<template>
  <base-modal class="form-builder-modal" :show.sync="visible">
    <template slot="title">
      <div class="form-builder-title">{{ $t('common.base.formFieldSet') }} > {{ $t('projectManage.setting.workLog.text') }}</div>
      <el-button class="form-builder-save-btn" plain @click="handleSubmit" :loading="pending">{{ $t('common.base.save') }}</el-button>
    </template>

    <!-- 表单设计器 S -->
    <form-design ref="formDesign" v-model="fields" mode="projectWorkLog" v-loading="loading" :max="1000"></form-design>
    <!-- 表单设计器 E -->
  </base-modal>
</template>
<script>
import { getProjectTypeField, saveProjectTypeField } from '@src/api/ProjectManage.ts';
import { onMounted, ref, reactive, toRefs } from 'vue';

import * as FormUtil from '@src/component/form/util';
import * as FormUtilValidate from '@src/mform/util/validate';
import { toast, notification } from '@src/util/platform';

export default {
  name: 'work-log-field-design',
  props: {
    templateId: {
      type: String | Number,
      default: '',
    },
  },
  setup(props) {
    const fields = ref([]);

    const state = reactive({
      loading: false,
      visible: false,
      pending: false,
    });

    const open = () => {
      state.visible = true;
      fetchFields();
    };

    // 获取表单字段
    const fetchFields = async () => {
      state.loading = true;
      try {
        let ret = await getProjectTypeField({
          tableName: 'projectWorkLog',
          templateId: props.templateId,
        });

        const { success, data } = ret;
        if (!success) return toast(message, 'error');

        fields.value = FormUtil.toFormField(data);
      } catch (err) {
        console.log('error => fetchFields', err);
      } finally {
        state.loading = false;
      }
    };

    // 将字段转换成后端可接收的字段
    const packToField = origin => {
      let fields = FormUtil.toField(origin);

      // 消耗工时setting特殊处理
      let costTimeSetting = {
        decimalConfig: {
          isLimit: 1,
          digit: '2',
        },
        limitConig: {
          isLimit: 1,
          max: '',
          min: '0.1',
          type: 1,
        }
      }

      fields.forEach((field, index) => {
        field.tableName = 'projectWorkLog';
        field.orderId = index;
        field.setting = field.formType === 'costTime' ? costTimeSetting : field.setting
      });

      return fields;
    };
    // 提交表单
    const handleSubmit = async () => {
      try {
        const allFields = packToField(fields.value)
        
        // 表单字段格式校验
        let checkMessage = FormUtil.validate(allFields);
        if (!FormUtilValidate.notification(checkMessage)) return;

        state.pending = true;

        let ret = await saveProjectTypeField({
          templateId: props.templateId,
          forms: allFields,
          mouldName: 'projectWorkLog',
        });

        const { success, message } = ret;
        if (!success) {
          return toast(message, 'error');
        } else {
          state.visible = false;
          toast(i18n.t('common.base.tip.updateSuccess'), 'success');
        }
      } catch (err) {
        console.log('error => submitField', err);
      } finally {
        state.pending = false;
      }
    };
    onMounted(() => {
      fetchFields();
    });

    return {
      fields,
      ...toRefs(state),
      open,
      handleSubmit,
    };
  },
};
</script>
<style lang="scss">
@import 'src/modules/setting/contract/contractFieldsSetting/ContractFieldsSetting.scss';
</style>